package secondriver.heathfood.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.*;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.Toast;
import secondriver.heathfood.R;
import secondriver.heathfood.bean.ApkInfoEntity;
import secondriver.heathfood.util.FileUtil;
import secondriver.heathfood.util.LogUtil;


/**
 * App 更新服务
 * <p>
 * 用户启动应用/手动点击更新，如果网络可用，检查服务器上的apk info文件缓存，对比版本，下载最版apk，提醒用户更新
 * <p>
 * Author : secondriver
 * Date :  2015/11/1
 */
public class UpgradeService extends Service {

    public static final String ACTION_UPGRADE_SERVICE = "secondriver.heathfood.action.UPGRADE_SERVICE";


    public static String DOWNLOAD_ID = "download_id";

    private BroadcastReceiver receiver;

    private final LogUtil logUtil = LogUtil.getLogger(UpgradeService.class.getName());

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    /**
     * 耗时操作最好在线程中进行或继承 {@link android.app.IntentService} 实现其{@link android.app.IntentService#onHandleIntent(Intent)}方法
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ApkInfoEntity apkInfoEntity = intent.getParcelableExtra(ApkInfoEntity.APK_INFO_KEY);
        if (null == apkInfoEntity) {
            stopSelf();
        } else {

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkInfoEntity.appUrl));
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI)
                    .setTitle(apkInfoEntity.versionName)
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            if (FileUtil.isUsableExternalStorage()) {
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkInfoEntity.getApkName());
            } else {
                //下载到默认目录
            }

            request.setVisibleInDownloadsUi(true);
            request.setMimeType("application/vnd.android.package-archive");

            DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            long downloadId = downloadManager.enqueue(request);
            PreferenceManager.getDefaultSharedPreferences(this).edit().putLong(DOWNLOAD_ID, downloadId).commit();

            receiver = new DownloadManagerBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
            registerReceiver(receiver, filter);
            stopSelf();
        }
        return Service.START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != receiver) {
            unregisterReceiver(receiver);
        }
    }

    static class DownloadManagerBroadcastReceiver extends BroadcastReceiver {

        private final LogUtil logUtil = LogUtil.getLogger(DownloadManagerBroadcastReceiver.class.getName());

        @Override
        public void onReceive(Context context, Intent intent) {
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                if (id == PreferenceManager.getDefaultSharedPreferences(context).getLong(DOWNLOAD_ID, -1)) {
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(id);
                    Cursor cursor = downloadManager.query(query);
                    if (cursor.moveToFirst()) {
                        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        if (status == DownloadManager.STATUS_SUCCESSFUL) {
                            String localURI = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            logUtil.info("Apk download localURI=%s .", localURI);
                            Intent updateAppIntent = new Intent(Intent.ACTION_VIEW);
                            updateAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                            updateAppIntent.setDataAndType(Uri.parse(localURI), "application/vnd.android.package-archive");
                            context.startActivity(updateAppIntent);
                        }
                    }
                    cursor.close();
                    PreferenceManager.getDefaultSharedPreferences(context).edit().remove
                            (DOWNLOAD_ID).commit();
                }
            }
            if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
                logUtil.info("download notification clicked.");
            }
        }
    }
}